/**
 * @Author: jipeng.Li
 * @Date: 2021-02-24 08:22:21
 * @LastEditors: jipeng.Li
 * @LastEditTime: 2021-03-12 09:53:21
 * @Description: 共享记录
 */
import React, { Component } from 'react';
import {
  View,
  SafeAreaView,
  Text,
  StyleSheet,
  Image,
  TouchableOpacity,
} from 'react-native';
import {
  px2dp,
  screenWidth,
  mainBgColorLightGray,
  fontColorCoffee,
  mainBgColorWhite,
  fontColorBlack,
  splitLineColorLightGray
} from '@/styles';
import oil from '@/api/oil';
import tool from '@/common/getDate';
import { msg } from '@/common';
import { calculatJD } from '@/common/util';
import { iconShare } from '@/images';
import XmList from '../../components/XmList';

export default class OilCardShareRecord extends Component {
  constructor(props) {
    super(props);
    this.state = {
      recordList: [],
      pageNo: 1,
      pageSize: 4,
      hasMorePage: true,
      showFoot: 1, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
      isLoading: false,
      cardData: {}
    };
  }

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { cardData } = params;
    this.setState({ cardData }, () => {
      this.loadData();
    });
    msg.on('refreshShareRecord', () => this.loadData());
  }

  componentWillUnmount() {
    msg.off('refreshShareRecord');
    msg.emit('setUpQrCodeInterval');
  }

  render() {
    const { isLoading, recordList, cardData, hasMorePage, showFoot } = this.state;
    return (
      <SafeAreaView style={styles.container}>
        {/* 共享按钮 */}
        {(cardData.accountCarownerId !== '') && this.renderShareBtn()}
        <XmList
          sources={recordList}
          renderItem={this.renderRecordItem}
          style={styles.container}
          isLoading={isLoading}
          onDropdownRefresh={this.loadData}
          hasMorePage={hasMorePage}
          onPullUpMore={this.LoadMore}
          singleKey={item => `recordList${item.id}`}
          showFoot={showFoot}
        />
      </SafeAreaView>
    );
  }

  // 分享按钮
  renderShareBtn = () => {
    const { cardData } = this.state;
    return (
      <TouchableOpacity
        style={{
          zIndex: 99,
          position: 'absolute',
          bottom: px2dp(40),
          left: screenWidth / 2 - px2dp(154),
        }}
        activeOpacity={0.8}
        onPress={() => {
          msg.emit('router: goToNext', {
            routeName: 'AddOilAuthorize',
            cardData
          });
        }}
      >
        <Image
          source={iconShare}
          style={{
            width: px2dp(308),
            height: px2dp(144)
          }}
        />
      </TouchableOpacity>
    );
  }

  // 渲染记录元素
  renderRecordItem = ({ item }) => {
    let isDisabled = item.isRecovery === 'Y';
    return (
      <View style={styles.recordItemContainer}>
        <View style={styles.recordItemEdge}>
          <Text
            style={{ color: isDisabled ? '#9D9A95' : fontColorBlack }}
          >
            {`${item.driverName} ${item.driverMobil}`}
          </Text>
          <Text style={{ color: isDisabled ? '#9D9A95' : fontColorBlack }}>{`${item.carNo || ''}`}</Text>
          {
            item.type === 2 && (
              <TouchableOpacity
                disabled={isDisabled}
                activeOpacity={0.8}
                onPress={() => this.recovery(item.id)}
                style={isDisabled ? styles.disabledRecoveryBtn : styles.recoveryBtn}
              >
                <Text
                  style={[styles.recoveryBtnText, isDisabled && { color: '#9D9A95' }]}
                >
                  {isDisabled ? '已回收' : '回收'}
                </Text>
              </TouchableOpacity>
            )
          }
        </View>
        <View style={styles.recordItemDataContainer}>
          <View style={styles.recordItemData}>
            {
              item.isQuota === 'Y' && (
                <Text style={{ fontSize: px2dp(24), color: '#999793' }}>{`上限：¥${item.authBalance}`}</Text>
              )
            }
            <Text
              style={{ color: isDisabled ? '#9D9A95' : fontColorCoffee, fontSize: px2dp(54) }}
            >
              {item.total || 0}
            </Text>
            <Text style={{ color: isDisabled ? '#9D9A95' : fontColorBlack, fontSize: px2dp(24) }}>
              {item.isQuota === 'Y' ? `累计核销(余¥${calculatJD(item.authBalance - item.totalAmount)})` : '累计核销(元)'}
            </Text>
          </View>
          <View style={styles.recordItemData}>
            {
              item.isQuota === 'Y' && (
                <Text style={{ fontSize: px2dp(24), color: '#999793' }} />
              )
            }
            <Text
              style={{ color: isDisabled ? '#9D9A95' : fontColorCoffee, fontSize: px2dp(54) }}
            >
              {`${item.number}`}
            </Text>
            <Text
              style={{
                color: isDisabled ? '#9D9A95' : fontColorBlack,
                fontSize: px2dp(24)
              }}
            >
              {item.isLimit === 'Y' ? `已用次数(余${item.empowerNum}次)` : '不限次数'}
            </Text>
          </View>
        </View>
        <View style={[styles.recordItemEdge]}>
          <View style={[styles.recordItemBottomEdge]}>
            <Text
              style={styles.recordItemBottomEdgeText}
            >
              {`授权：${tool.dateForm(item.empowerStartTime, 'yyyy.MM.dd')}`}
            </Text>
            <Text
              style={styles.recordItemBottomEdgeText}
            >
              {`截止：${tool.dateForm(item.empowerEndTime, 'yyyy.MM.dd')}`}
            </Text>
          </View>
        </View>
      </View>
    );
  }

  // 回收按钮方法
  recovery = (id) => {
    msg.emit('app:messageBox', {
      isVisible: true,
      title: '确认回收授权？',
      text: '油卡回收后，该用户将无法再次使用油卡加油',
      okText: '确定',
      cancelText: '取消',
      okFn: () => {
        oil.recycling({ id }).then(res => {
          if (res.success) {
            this.loadData();
          } else {
            msg.emit('app:messageBox', {
              isVisible: true,
              title: '提示',
              text: res.msg || '回收失败，请重试',
              okText: '确定',
              isClickBg: false,
            });
          }
        });
      },
      cancelFn: () => {

      },
    });
  }

  // 下拉刷新
  loadData = () => {
    this.setState({
      isLoading: true,
      pageNo: 1,
      recordList: [],
      showFoot: 0
    }, () => {
      this.pageOwnerAuthorization('dropdown');
    });
  }

  // 上拉加载更多
  LoadMore = () => {
    this.setState({ showFoot: 2 }, () => this.pageOwnerAuthorization('pullMore'));
  }

  /**
   * 接口
   */
  pageOwnerAuthorization = (type) => {
    const { recordList, pageNo, pageSize, cardData } = this.state;
    let newRecordList = [];
    oil.pageOwnerAuthorization({ id: cardData.accountCarownerId, pageNo: pageNo, pageSize: pageSize }).then(res => {
      if (res.success) {
        const { records, pages } = res.data;
        if (type === 'dropdown') {
          this.setState({ recordList: records });
        }
        if (type === 'pullMore') {
          if (pageNo > pages) {
            this.setState({ showFoot: 1 });
            return;
          }
          newRecordList = [...recordList, ...records];
          this.setState({ recordList: newRecordList });
        }
        this.setState({ isLoading: false, pageNo: pageNo + 1 });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
    padding: px2dp(20),
  },
  recordItemContainer: {
    height: px2dp(309),
    backgroundColor: mainBgColorWhite,
    borderRadius: px2dp(10),
    marginBottom: px2dp(20)
  },
  recordItemEdge: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: mainBgColorWhite,
    marginHorizontal: px2dp(20),
    justifyContent: 'space-between',
  },
  recoveryBtn: {
    alignItems: 'center',
    justifyContent: 'center',
    borderColor: fontColorCoffee,
    borderRadius: px2dp(10),
    borderWidth: px2dp(2),
    width: px2dp(112),
    height: px2dp(45)
  },
  disabledRecoveryBtn: {
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: mainBgColorLightGray,
    borderRadius: px2dp(10),
    width: px2dp(112),
    height: px2dp(45)
  },
  recoveryBtnText: {
    fontSize: px2dp(24),
    color: fontColorCoffee
  },
  recordItemBottomEdge: {
    flexDirection: 'row',
    alignItems: 'center',
    flex: 8 / 10,
    justifyContent: 'space-between'
  },
  recordItemBottomEdgeText: {
    color: '#9D9A95',
    fontSize: px2dp(24)
  },
  recordItemDataContainer: {
    height: px2dp(160),
    flexDirection: 'row',
    backgroundColor: mainBgColorWhite,
    borderTopWidth: px2dp(1),
    borderTopColor: splitLineColorLightGray,
    borderBottomColor: splitLineColorLightGray,
    borderBottomWidth: px2dp(1),
    marginHorizontal: px2dp(20)
  },
  recordItemData: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
  },
  recordItemDataText: {},
});
